package vis.core.common.valid;

import vis.core.domain.sys.MSG;
import vis.core.domain.sys.ServiceException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式工具类
 * <p>
 * 使用：
 * boolean isTrue = ValidKit.id_card_name.check(“123”);
 * <p>
 * ValidKit.id_card_name.check(“123”, MSG.USER_ID_CARD_NAME);
 * <p>
 * ValidKit.id_card_number.check(“123”, "身份证号输入错误");
 */
public enum ValidKit {

    idCardNumber("身份证号", "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$"),
    idCardName("身份证名称", "^[\\u4e00-\\u9fa5]{2,8}$"),

    intGt100("大于100的整数", "^[1-9]\\d{2,}$"),
    intGe100("大于等于100的整数", "^([1-9]\\d{2,})|100$"),

    rateTenNotZero("不等于0的，1位小数", "^((0\\.(?!0+$)\\d{1,1})|1.0)$"),
    rateHundredNotZero("不等于0的，2位小数", "^((0\\.(?!0+$)\\d{1,2})|1.00|1.0)$"),
    rateThousandNotZero("不等于0的，3位小数", "^((0\\.(?!0+$)\\d{1,3})|1.000|1.00|1.0)$"),

    email("邮箱", "^([a-zA-Z]|[0-9])(\\w|\\-)+@[a-zA-Z0-9]+\\.([a-zA-Z]{2,4})$"),
    phone("手机号", "^0?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$"),
    telPhone("固定电话", "^0\\d{2,3}-\\d{7,8}$"),
    url("http地址", "^(https?|ftp):\\/\\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+\\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$"),

    chineseText("中文", "^[\u4e00-\u9fa5]$"),

    ;

    private final String regex;

    private final String desc;

    public boolean check(String value) {
        if (value == null) return false;
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(value);
        return matcher.matches();
    }

    public void check(String value, MSG msg) {
        if (value == null) throw new ServiceException(msg);
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(value);
        boolean matches = matcher.matches();
        if (!matches) throw new ServiceException(msg);
    }

    public void check(String value, String msg) {
        if (value == null) throw new ServiceException(msg);
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(value);
        boolean matches = matcher.matches();
        if (!matches) throw new ServiceException(msg);
    }

    ValidKit(String desc, String regex) {
        this.desc = desc;
        this.regex = regex;
    }

    public String getRegex() {
        return regex;
    }

    public String getDesc() {
        return desc;
    }

}
